-- 简单代理实现

local bucket = {};

-- 作为内部存储数据的
local symbol = {}
local metatable = {
    __index = function(target, key)
        print("track", target, key)
        -- 待触发函数
        table.insert(bucket, effect)
        return target[symbol][key]
    end,
    __newindex = function(target, key, value)
        print("trigger", target, key)
        local oldValue = target[symbol][key]
        target[symbol][key] = value

        if (oldValue ~= value) then
            for i = 1, #bucket, 1 do
                local fn = bucket[i]
                if (type(fn) == "function") then
                    fn();
                end
            end
        end
    end
}

-- 代理数据
local function reactive(table)
    local proxy = {}
    proxy[symbol] = table
    setmetatable(proxy, metatable)
    return proxy
end

-- 转换为代理数据
local data = reactive({text = "hello"})

function effect()
    local i = data.text;
    print("effect", i);
end

effect();
data.text = "fix value"
